import {
  ConditionTypeEnum,
  NodeTypeEnum,
} from '../constant/index.js';
import { getIconByType } from '../nodes/icons.js';
import { getNodeShapeByType } from '../nodes/shapes.js';

const createItem = ({ type, label }) => ({
  type,
  label,
  icon: getIconByType(type),
  shape: getShapeByType(type),  // 使用统一的函数映射
});

// 根据 type 获取正确的 shape 名称
const getShapeByType = (type) => {
  // 顺序类和其他类使用 ConditionTypeEnum，直接返回
  if ([
    ConditionTypeEnum.THEN,
    ConditionTypeEnum.WHEN,
    ConditionTypeEnum.CATCH,
    ConditionTypeEnum.AND,
    ConditionTypeEnum.OR,
    ConditionTypeEnum.NOT,
    ConditionTypeEnum.CHAIN,
  ].includes(type)) {
    return type;
  }
  
  // 分支类和循环类需要映射到 NodeTypeEnum
  const typeMap = {
    [ConditionTypeEnum.SWITCH]: NodeTypeEnum.SWITCH,
    [ConditionTypeEnum.IF]: NodeTypeEnum.IF,
    [ConditionTypeEnum.FOR]: NodeTypeEnum.FOR,
    [ConditionTypeEnum.WHILE]: NodeTypeEnum.WHILE,
    [ConditionTypeEnum.ITERATOR]: NodeTypeEnum.ITERATOR,
  };
  
  return typeMap[type] || type;
};

export const NODE_GROUP = {
  key: 'node',
  name: '节点类',
  cellTypes: [
    createItem({ type: NodeTypeEnum.COMMON, label: '普通节点' }),
  ],
};

export const SEQUENCE_GROUP = {
  key: 'sequence',
  name: '顺序类',
  cellTypes: [
    createItem({ type: ConditionTypeEnum.THEN, label: '串行 THEN' }),
    createItem({ type: ConditionTypeEnum.WHEN, label: '并行 WHEN' }),
  ],
};

export const BRANCH_GROUP = {
  key: 'branch',
  name: '分支类',
  cellTypes: [
    createItem({ type: ConditionTypeEnum.SWITCH, label: '选择 SWITCH' }),
    createItem({ type: ConditionTypeEnum.IF, label: '条件 IF' }),
  ],
};

export const CONTROL_GROUP = {
  key: 'control',
  name: '循环类',
  cellTypes: [
    createItem({ type: ConditionTypeEnum.FOR, label: '循环 FOR' }),
    createItem({ type: ConditionTypeEnum.WHILE, label: '循环 WHILE' }),
    createItem({ type: ConditionTypeEnum.ITERATOR, label: '迭代 ITERATOR' }),
  ],
};

export const OTHER_GROUP = {
  key: 'other',
  name: '其他类',
  cellTypes: [
    createItem({ type: ConditionTypeEnum.CATCH, label: '异常 CATCH' }),
    createItem({ type: ConditionTypeEnum.AND, label: '与 AND' }),
    createItem({ type: ConditionTypeEnum.OR, label: '或 OR' }),
    createItem({ type: ConditionTypeEnum.NOT, label: '非 NOT' }),
    createItem({ type: ConditionTypeEnum.CHAIN, label: '子流程 CHAIN' }),
  ],
};

export const PALETTE_GROUPS = [
  NODE_GROUP,
  SEQUENCE_GROUP,
  BRANCH_GROUP,
  CONTROL_GROUP,
  OTHER_GROUP,
];

